package com.yhhl.common;

import java.util.List;
import java.util.Map;

import org.I0Itec.zkclient.ZkClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jboss.netty.util.internal.ConcurrentHashMap;

@Deprecated
public class ZkClientManageImpl implements IZkClientConfigManage {

	private final static Logger logger = LogManager.getLogger(ZkClientManageImpl.class);
	
	// 是否可以读
	private volatile boolean canRead = true;

	/**
	 * 存储配置内容
	 */
	private volatile Map<String, String> configMap = new ConcurrentHashMap<String, String>();
	private ZkClient zkClient;
	private ZkClientConfigWatcher configWatcher;
	private final static String SEPARATOR = "/";

	public ZkClientManageImpl(String serverString) {
		this.zkClient = new ZkClient(serverString, 30000, 30000, new ZkClientCustomSerializer());
		this.configWatcher = new ZkClientConfigWatcher(zkClient, this);
		this.init();
	}

	@Override
	public void init() {
		if (!zkClient.exists(configRoot)) {
			zkClient.createPersistent(configRoot);
		}
		logger.info("start to init configMap");
		this.getAll();
		logger.info("init configMap over");
		this.configWatcher.watcher(configRoot);
	}

	// 拼接路径
	private String contactKey(String key) {
		return configRoot.concat(SEPARATOR).concat(key);
	}

	@Override
	public void reload() {
		List<String> configList = this.zkClient.getChildren(configRoot);
		if(configList!=null && configList.size()>0){
			canRead = false;
			// 重新加载前将Map清空
			configMap.clear();
			for (String config : configList) {
				String value = this.zkClient.readData(this.contactKey(config));
				String key = config.substring(config.indexOf("/") + 1);
				configMap.put(key, value);
			}
			canRead = true;
		}
		
	}

	@Override
	public Map<String, String> getAll() {
		while(!canRead){
			continue;
		}
		if (configMap != null && configMap.size() > 0) {
			return configMap;
		}
		reload();
		return configMap;
	}

	@Override
	public String get(String key) {
		if (this.configMap.get(key) == null) {
			String contactKey = this.contactKey(key);
			if (!this.zkClient.exists(contactKey)) {
				return null;
			}
			return this.zkClient.readData(contactKey);
		}
		return configMap.get(key);
	}

	@Override
	public void add(String key, String value) {
		String contactKey = this.contactKey(key);
		this.zkClient.createPersistent(contactKey, value);
		configWatcher.watcher(contactKey);
	}

	@Override
	public void update(String key, String value) {
		String contactKey = this.contactKey(key);
		this.zkClient.writeData(contactKey, value);
		configWatcher.watcher(contactKey);
	}

	@Override
	public void delete(String key) {
		String contactKey = this.contactKey(key);
		this.zkClient.delete(contactKey);
	}

}
